package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.util.CodeGenerator;
import com.zzyl.vo.CheckInConfigVo;
import com.zzyl.vo.CheckInDetailVo;
import com.zzyl.vo.CheckInElderVo;
import com.zzyl.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 入住Service业务层处理
 *
 * @author FuJiaWei
 * @date 2025-05-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //判断老人是否入住
        String elderIdCard = dto.getCheckInElderDto().getIdCardNo();
        Elder elderInDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, elderIdCard));
        if (null != elderInDb) {
            Integer elderStatus = elderInDb.getStatus();
            if (elderStatus == 1 || elderStatus == 2 || elderStatus == 4) {
                throw new ServiceException("老人已入住");
            }
        }
        //更新床位状态
        Long bedId = dto.getCheckInConfigDto().getBedId();
        int count = bedMapper.updateBedStatus(bedId);
        if (count == 0) {
            throw new ServiceException("该床位已被占用，请选择其它床位");
        }
        //新增或更新老人
        Elder elder = addOrUpdateElder(dto.getCheckInElderDto(), elderInDb, bedId);
        //新增签约
        addContract(dto, elder);
        //新增入住信息
        CheckIn checkIn = addCheckIn(dto, elder);
        //新增入住配置
        addCheckInConfig(dto, checkIn);
    }

    //新增入住配置
    private void addCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    //新增入住信息
    private CheckIn addCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    //新增签约
    private void addContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setElderName(elder.getName());
        contract.setElderId(elder.getId().intValue());
        contract.setContractNumber("GDL" + CodeGenerator.generateContractNumber());
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        LocalDateTime now = LocalDateTime.now();
        if (endDate.isBefore(now)) {
            throw new ServiceException("李再赣神魔？");
        }
        if (startDate.isBefore(now)) {
            contract.setStatus(1);
        } else {
            contract.setStatus(0);
        }
        contractMapper.insert(contract);
    }

    //新增或更新老人
    private Elder addOrUpdateElder(CheckInElderDto checkInElderDto, Elder elderInDb, Long bedId) {
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        elder.setBedId(bedId);
        elder.setBedNumber(bedMapper.selectById(bedId).getBedNumber());
        elder.setStatus(1);
        if (null != elderInDb) {
            elder.setId(elderInDb.getId());
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住消息
        CheckIn checkIn = checkInMapper.selectById(id);
        if (null == checkIn) {
            throw new ServiceException("无入住消息");
        }
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkIn, CheckInConfigVo.class);
        //查询老人消息
        Optional.ofNullable(elderMapper.selectById(checkIn.getElderId())).ifPresent(elder -> {
            CheckInElderVo elderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
            elderVo.setAge(IdcardUtil.getAgeByIdCard(elderVo.getIdCardNo()));
            checkInDetailVo.setCheckInElderVo(elderVo);
        });
        //查询合同
        Optional.ofNullable(contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, checkIn.getElderId()))).ifPresent(checkInDetailVo::setContract);

        //查询入住配置
        Optional.ofNullable(checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id))).ifPresent(checkInConfig -> BeanUtils.copyProperties(checkInConfig, checkInConfigVo));

        //转换家属列表
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        //整合数据返回
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        return checkInDetailVo;
    }
}
